package com.ruoyi.system.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.DbIdentityManagementMapper;
import com.ruoyi.system.domain.DbIdentityManagement;
import com.ruoyi.system.domain.ScoreManagement;
import com.ruoyi.system.domain.DbQualificationManagement;
import com.ruoyi.system.service.IDbIdentityManagementService;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.system.service.IDbPhysicalManagementService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import com.ruoyi.system.domain.dto.StatisticsDTO;
import com.ruoyi.system.domain.dto.StatisticsDTO.PositionData;

import javax.validation.Validator;

/**
 * 四级联考递补身份验证Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-02
 */
@Service
public class DbIdentityManagementServiceImpl implements IDbIdentityManagementService 
{
    private static final Logger log = LoggerFactory.getLogger(DbIdentityManagementServiceImpl.class);

    @Autowired
    private DbIdentityManagementMapper dbIdentityManagementMapper;
    
    @Autowired
    protected Validator validator;
    
    @Autowired
    private IDbPhysicalManagementService dbPhysicalManagementService;

    /**
     * 查询四级联考递补身份验证
     * 
     * @param id 四级联考递补身份验证主键
     * @return 四级联考递补身份验证
     */
    @Override
    public DbIdentityManagement selectDbIdentityManagementById(Long id)
    {
        return dbIdentityManagementMapper.selectDbIdentityManagementById(id);
    }

    /**
     * 查询四级联考递补身份验证列表
     * 
     * @param dbIdentityManagement 四级联考递补身份验证
     * @return 四级联考递补身份验证
     */
    @Override
    public List<DbIdentityManagement> selectDbIdentityManagementList(DbIdentityManagement dbIdentityManagement)
    {
        return dbIdentityManagementMapper.selectDbIdentityManagementList(dbIdentityManagement);
    }

    /**
     * 新增四级联考递补身份验证
     * 
     * @param dbIdentityManagement 四级联考递补身份验证
     * @return 结果
     */
    @Override
    public int insertDbIdentityManagement(DbIdentityManagement dbIdentityManagement)
    {
        return dbIdentityManagementMapper.insertDbIdentityManagement(dbIdentityManagement);
    }

    /**
     * 修改四级联考递补身份验证
     * 
     * @param dbIdentityManagement 四级联考递补身份验证
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDbIdentityManagement(DbIdentityManagement dbIdentityManagement)
    {
        // 获取原有数据
        DbIdentityManagement originalData = selectDbIdentityManagementById(dbIdentityManagement.getId());
        
        // 执行更新操作
        int rows = dbIdentityManagementMapper.updateDbIdentityManagement(dbIdentityManagement);
        
        // 如果更新成功，且身份验证结果从非"通过"变为"通过"，则自动流转到递补体能测评模块
        if (rows > 0 && "通过".equals(dbIdentityManagement.getIdentityVerificationResult()) 
            && (originalData == null || !"通过".equals(originalData.getIdentityVerificationResult())))
        {
            log.info("考生{}（身份证号：{}）递补身份验证结果修改为\"通过\"，自动流转到递补体能测评模块", 
                     dbIdentityManagement.getName(), dbIdentityManagement.getIdCard());
            
            try
            {
                // 创建只包含当前考生的列表
                List<DbIdentityManagement> verifiedList = new java.util.ArrayList<>();
                verifiedList.add(dbIdentityManagement);
                
                // 调用递补体能测评服务，将考生添加到递补体能测评名单
                dbPhysicalManagementService.insertDbPhysicalListFromDbIdentity(verifiedList, "系统自动");
                log.info("考生{}（身份证号：{}）成功流转到递补体能测评模块", 
                         dbIdentityManagement.getName(), dbIdentityManagement.getIdCard());
            }
            catch (Exception e)
            {
                log.error("考生流转到递补体能测评模块失败", e);
                // 这里不抛出异常，确保即使流转失败，更新操作仍然成功
            }
        }
        
        return rows;
    }

    /**
     * 批量删除四级联考递补身份验证
     * 
     * @param ids 需要删除的四级联考递补身份验证主键
     * @return 结果
     */
    @Override
    public int deleteDbIdentityManagementByIds(Long[] ids)
    {
        return dbIdentityManagementMapper.deleteDbIdentityManagementByIds(ids);
    }

    /**
     * 删除四级联考递补身份验证信息
     * 
     * @param id 四级联考递补身份验证主键
     * @return 结果
     */
    @Override
    public int deleteDbIdentityManagementById(Long id)
    {
        return dbIdentityManagementMapper.deleteDbIdentityManagementById(id);
    }

    /**
     * 导入四级联考递补身份验证数据
     * 
     * @param dbIdentityList 递补身份验证数据列表
     * @param updateSupport 是否更新支持，如果已存在，是否覆盖
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public String importDbIdentityData(List<DbIdentityManagement> dbIdentityList, boolean updateSupport, String operName)
    {
        if (StringUtils.isNull(dbIdentityList) || dbIdentityList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        
        for (DbIdentityManagement dbIdentity : dbIdentityList)
        {
            try
            {
                // 验证是否存在相同的准考证号或身份证号
                DbIdentityManagement existDbIdentity = new DbIdentityManagement();
                if (StringUtils.isNotEmpty(dbIdentity.getExamNumber()))
                {
                    existDbIdentity.setExamNumber(dbIdentity.getExamNumber());
                }
                else if (StringUtils.isNotEmpty(dbIdentity.getIdCard()))
                {
                    existDbIdentity.setIdCard(dbIdentity.getIdCard());
                }
                else
                {
                    throw new ServiceException("导入数据中准考证号和身份证号不能同时为空");
                }
                
                List<DbIdentityManagement> existList = dbIdentityManagementMapper.selectDbIdentityManagementList(existDbIdentity);
                
                if (StringUtils.isNull(existList) || existList.size() == 0)
                {
                    // 如果不存在，执行插入操作
                    dbIdentityManagementMapper.insertDbIdentityManagement(dbIdentity);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、准考证号 " + dbIdentity.getExamNumber() + " 导入成功");
                }
                else if (updateSupport)
                {
                    // 如果存在且允许更新
                    dbIdentity.setId(existList.get(0).getId()); // 设置ID，确保更新正确的记录
                    dbIdentityManagementMapper.updateDbIdentityManagement(dbIdentity);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、准考证号 " + dbIdentity.getExamNumber() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、准考证号 " + dbIdentity.getExamNumber() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、准考证号 " + dbIdentity.getExamNumber() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 从成绩合格名单生成并插入递补身份验证名单
     * 
     * @param scoreList 符合条件的成绩合格名单数据列表
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public int insertDbIdentityListFromScore(List<ScoreManagement> scoreList, String operName)
    {
        if (StringUtils.isNull(scoreList) || scoreList.size() == 0)
        {
            throw new ServiceException("符合条件的考生数据不能为空！");
        }
        
        int successNum = 0;
        
        // 先清空现有递补身份验证名单数据
        DbIdentityManagement clearCriteria = new DbIdentityManagement();
        List<DbIdentityManagement> existingList = dbIdentityManagementMapper.selectDbIdentityManagementList(clearCriteria);
        if (existingList != null && existingList.size() > 0)
        {
            Long[] ids = new Long[existingList.size()];
            for (int i = 0; i < existingList.size(); i++)
            {
                ids[i] = existingList.get(i).getId();
            }
            dbIdentityManagementMapper.deleteDbIdentityManagementByIds(ids);
        }
        
        // 遍历符合条件的考生，插入递补身份验证名单
        for (ScoreManagement score : scoreList)
        {
            try
            {
                // 创建递补身份验证名单对象
                DbIdentityManagement dbIdentity = new DbIdentityManagement();
                
                // 复制考生信息
                dbIdentity.setCandidateId(score.getCandidateId());
                dbIdentity.setName(score.getName());
                dbIdentity.setGender(score.getGender());
                dbIdentity.setIdCard(score.getIdCard());
                dbIdentity.setExamNumber(score.getExamNumber());
                dbIdentity.setAdministrativeAptitudeScore(score.getAdministrativeAptitudeScore());
                dbIdentity.setEssayScore(score.getEssayScore());
                dbIdentity.setProfessionalSubjectScore(score.getProfessionalSubjectScore());
                dbIdentity.setTotalScore(score.getTotalScore());
                dbIdentity.setProfessionalSkillTestScore(score.getProfessionalSkillTestScore());
                dbIdentity.setAppliedUnit(score.getAppliedUnit());
                dbIdentity.setAppliedPosition(score.getAppliedPosition());
                dbIdentity.setRecruitmentNumber(score.getRecruitmentNumber());
                dbIdentity.setInterviewRatio(score.getInterviewRatio());
                dbIdentity.setRanking(score.getRanking());
                dbIdentity.setGraduationSchool(score.getGraduationSchool());
                dbIdentity.setHasProfessionalSkillTest(score.getHasProfessionalSkillTest());
                dbIdentity.setPositionCategory(score.getPositionCategory());
                dbIdentity.setIsAlternate("Y");  // 设置为递补
//                dbIdentity.setIdentityVerificationResult("待验证");  // 默认为待验证
//                dbIdentity.setPhysicalTestResult("待测试");  // 默认为待测试
                
                // 插入递补身份验证名单
                dbIdentityManagementMapper.insertDbIdentityManagement(dbIdentity);
                successNum++;
            }
            catch (Exception e)
            {
                log.error("递补身份验证名单导入失败：", e);
                throw new ServiceException("导入递补身份验证名单失败，请联系管理员");
            }
        }
        
        return successNum;
    }

    /**
     * 从递补资格审查名单生成并插入递补身份验证名单
     * 
     * @param dbQualificationList 符合条件的递补资格审查名单数据列表
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public int insertDbIdentityListFromDbQualification(List<DbQualificationManagement> dbQualificationList, String operName)
    {
        if (StringUtils.isNull(dbQualificationList) || dbQualificationList.size() == 0)
        {
            throw new ServiceException("符合条件的考生数据不能为空！");
        }
        
        int successNum = 0;
        
        // 先清空现有递补身份验证名单数据
        /*DbIdentityManagement clearCriteria = new DbIdentityManagement();
        List<DbIdentityManagement> existingList = dbIdentityManagementMapper.selectDbIdentityManagementList(clearCriteria);
        if (existingList != null && existingList.size() > 0)
        {
            Long[] ids = new Long[existingList.size()];
            for (int i = 0; i < existingList.size(); i++)
            {
                ids[i] = existingList.get(i).getId();
            }
            dbIdentityManagementMapper.deleteDbIdentityManagementByIds(ids);
        }*/
        
        // 遍历符合条件的考生，插入递补身份验证名单
        for (DbQualificationManagement dbQualification : dbQualificationList)
        {
            try
            {
                // 创建递补身份验证名单对象
                DbIdentityManagement dbIdentity = new DbIdentityManagement();
                
                // 复制考生信息
                dbIdentity.setCandidateId(dbQualification.getCandidateId());
                dbIdentity.setName(dbQualification.getName());
                dbIdentity.setGender(dbQualification.getGender());
                dbIdentity.setIdCard(dbQualification.getIdCard());
                dbIdentity.setExamNumber(dbQualification.getExamNumber());
                dbIdentity.setAdministrativeAptitudeScore(dbQualification.getAdministrativeAptitudeScore());
                dbIdentity.setEssayScore(dbQualification.getEssayScore());
                dbIdentity.setProfessionalSubjectScore(dbQualification.getProfessionalSubjectScore());
                dbIdentity.setTotalScore(dbQualification.getTotalScore());
                dbIdentity.setProfessionalSkillTestScore(dbQualification.getProfessionalSkillTestScore());
                dbIdentity.setAppliedUnit(dbQualification.getAppliedUnit());
                dbIdentity.setAppliedPosition(dbQualification.getAppliedPosition());
                dbIdentity.setRecruitmentNumber(dbQualification.getRecruitmentNumber());
                dbIdentity.setInterviewRatio(dbQualification.getInterviewRatio());
                dbIdentity.setRanking(dbQualification.getRanking());
                dbIdentity.setGraduationSchool(dbQualification.getGraduationSchool());
                dbIdentity.setHasProfessionalSkillTest(dbQualification.getHasProfessionalSkillTest());
                dbIdentity.setPositionCategory(dbQualification.getPositionCategory());
                dbIdentity.setIsAlternate("Y");  // 设置为递补
//                dbIdentity.setIdentityVerificationResult("待验证");  // 默认为待验证
//                dbIdentity.setPhysicalTestResult("待测试");  // 默认为待测试
                
                // 插入递补身份验证名单
                dbIdentityManagementMapper.insertDbIdentityManagement(dbIdentity);
                successNum++;
            }
            catch (Exception e)
            {
                log.error("递补身份验证名单导入失败：", e);
                throw new ServiceException("导入递补身份验证名单失败，请联系管理员");
            }
        }
        
        return successNum;
    }

    /**
     * 生成递补体能测评名单
     * 从递补身份验证名单中筛选出身份验证结果为"通过"的考生，生成递补体能测评名单
     * 
     * @param operName 操作用户
     * @return 生成的递补体能测评名单人数
     */
    @Override
    @Transactional
    public int generateDbPhysicalList(String operName)
    {
        // 找出所有递补身份验证结果为"通过"的考生
        DbIdentityManagement criteria = new DbIdentityManagement();
        criteria.setIdentityVerificationResult("通过");
        List<DbIdentityManagement> verifiedList = selectDbIdentityManagementList(criteria);
        
        if (StringUtils.isNull(verifiedList) || verifiedList.size() == 0)
        {
            log.info("没有找到符合条件的递补考生");
            throw new ServiceException("没有找到递补身份验证结果为\"通过\"的考生");
        }
        
        log.info("找到{}个递补身份验证结果为\"通过\"的考生", verifiedList.size());
        
        // 调用递补体能测评服务，插入递补体能测评名单
        return dbPhysicalManagementService.insertDbPhysicalListFromDbIdentity(verifiedList, operName);
    }

    /**
     * 获取四级联考递补身份验证统计数据
     * 
     * @return 统计数据
     */
    @Override
    public StatisticsDTO getDbIdentityStatistics()
    {
        // 创建返回对象
        StatisticsDTO statisticsDTO = new StatisticsDTO();
        
        // 查询所有递补身份验证数据
        List<DbIdentityManagement> dbIdentityList = dbIdentityManagementMapper.selectDbIdentityManagementList(new DbIdentityManagement());
        
        // 总数
        int total = dbIdentityList.size();
        statisticsDTO.setTotal(total);
        
        // 通过和未通过数量
        int passed = 0;
        // 职位分布统计
        Map<String, Integer> positionMap = new HashMap<>();
        
        for (DbIdentityManagement dbIdentity : dbIdentityList)
        {
            // 统计通过人数
            if ("通过".equals(dbIdentity.getIdentityVerificationResult()))
            {
                passed++;
            }
            
            // 统计职位分布
            String position = dbIdentity.getAppliedPosition();
            if (position != null && !position.isEmpty())
            {
                positionMap.put(position, positionMap.getOrDefault(position, 0) + 1);
            }
        }
        
        statisticsDTO.setPassed(passed);
        statisticsDTO.setFailed(total - passed);
        
        // 转换职位分布数据为前端所需格式
        List<PositionData> positionDataList = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : positionMap.entrySet())
        {
            positionDataList.add(new PositionData(entry.getKey(), entry.getValue()));
        }
        statisticsDTO.setPositionData(positionDataList);
        
        return statisticsDTO;
    }
}
